<!DOCTYPE html>
<html lang="zh-cn" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.thymeleaf.org" layout:decorator="admin/fragments/layout">
<head>
    <title>文件管理-文件共享</title>
    <meta name="active" content="tenant-manage"/>
    <link rel="stylesheet" type="text/css"
          th:href="@{/resources/vendor/plugins/datatables/media/css/dataTables.bootstrap.css}"/>

    <!-- 弹出框 CSS -->
    <link rel="stylesheet" type="text/css" th:href="@{/resources/vendor/plugins/magnific/magnific-popup.css}"/>

    <!-- 弹出框 -->
    <script th:src="@{/resources/vendor/plugins/magnific/jquery.magnific-popup.js}"></script>

    <!-- 提示 PNotify -->
    <script th:src="@{/resources/vendor/plugins/pnotify/pnotify.js}"></script>

    <!--jquery 确认框-->
    <script th:src="@{/resources/jquery-confirm-master/js/jquery-confirm.js}"></script>
    <link rel="stylesheet" type="text/css" th:href="@{/resources/jquery-confirm-master/css/jquery-confirm.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/resources/jquery-confirm-master/css/jquery-confirm.less}"/>

    <!-- Fancytree CSS -->
    <link rel="stylesheet" type="text/css" href="vendor/plugins/fancytree/skin-win7/ui.fancytree.min.css"
          th:href="@{/resources/vendor/plugins/fancytree/skin-win8/ui.fancytree.min.css}"/>
    <!-- Fancytree Plugin -->
    <script src="vendor/plugins/fancytree/jquery.fancytree-all.min.js"
            th:src="@{/resources/vendor/plugins/fancytree/jquery.fancytree-all.min.js}"></script>
    <!-- Fancytree Addon - Childcounter -->
    <script src="vendor/plugins/fancytree/extensions/jquery.fancytree.childcounter.js"
            th:src="@{/resources/vendor/plugins/fancytree/extensions/jquery.fancytree.childcounter.js}"></script>
    <!-- Fancytree Addon - ColumnView -->
    <script src="vendor/plugins/fancytree/extensions/jquery.fancytree.columnview.js"
            th:src="@{/resources/vendor/plugins/fancytree/extensions/jquery.fancytree.columnview.js}"></script>
    <!-- Fancytree Addon - Drag and Drop -->
    <script src="vendor/plugins/fancytree/extensions/jquery.fancytree.dnd.js"
            th:src="@{/resources/vendor/plugins/fancytree/extensions/jquery.fancytree.dnd.js}"></script>
    <!-- Fancytree Addon - Inline Edit -->
    <script src="vendor/plugins/fancytree/extensions/jquery.fancytree.edit.js"
            th:src="@{/resources/vendor/plugins/fancytree/extensions/jquery.fancytree.edit.js}"></script>
    <!-- Fancytree Addon - Inline Edit -->
    <script src="vendor/plugins/fancytree/extensions/jquery.fancytree.filter.js"
            th:src="@{/resources/vendor/plugins/fancytree/extensions/jquery.fancytree.filter.js}"></script>

    <!--dataTables-->
    <!-- Datatables CSS -->
    <link rel="stylesheet" type="text/css" href="vendor/plugins/datatables/media/css/dataTables.bootstrap.min.css"
          th:href="@{/resources/vendor/plugins/datatables/media/css/dataTables.bootstrap.min.css}"/>

    <!-- Datatables -->
    <script src="vendor/plugins/datatables/media/js/jquery.dataTables.js"
            th:src="@{/resources/vendor/plugins/datatables/media/js/jquery.dataTables.js}"></script>
    <script src="vendor/plugins/datatables/media/js/dataTables.ellipsis.js"
            th:src="@{/resources/vendor/plugins/datatables/media/js/dataTables.ellipsis.js}"></script>

    <!-- Datatables Bootstrap Modifications  -->
    <script src="vendor/plugins/datatables/media/js/dataTables.bootstrap.js"
            th:src="@{/resources/vendor/plugins/datatables/media/js/dataTables.bootstrap.js}"></script>

    <!-- jquery-confirm -->
    <script src="vendor/plugins/jqueryconfirm/jquery-confirm.min.js"
            th:src="@{/resources/vendor/plugins/jqueryconfirm/jquery-confirm.min.js}"></script>
    <link rel="stylesheet" type="text/css" href="vendor/plugins/jqueryconfirm/jquery-confirm.min.css"
          th:href="@{/resources/vendor/plugins/jqueryconfirm/jquery-confirm.min.css}"/>

    <!-- sha1 -->
    <script th:src="@{/resources/js/sha1.js}"/>

    <!-- flexpaper -->
    <script th:src="@{/resources/flexpaper/js/flexpaper.js}"/>
    <script th:src="@{/resources/flexpaper/js/flexpaper_handlers.js}"/>
</head>
<body>

<header id="topbar" class="ph10" layout:fragment="topbar">
    <div class="topbar-left">
        <ol class="breadcrumb">
            <li class="crumb-icon crumb-active">
                <a th:href="@{/admin/dashboard}"> <span class="glyphicon glyphicon-home"></span> </a>
            </li>
            <li class="crumb-trail">文件管理</li>
            <li class="crumb-trail">文件共享</li>
        </ol>
    </div>
    <div>
        <div class="topbar-right hidden-xs hidden-sm pr10">
            <a href="javascript:void(0)" title="点击左侧文件夹在相应目录上传" class="btn btn-default btn-sm fw400 ml10 uploadFile">
                <span class="fa fa-files-o pr5"></span> 上传文件
            </a>
        </div>
        <div class="topbar-right hidden-xs hidden-sm pr10">
            <a href="javascript:void(0)" title="点击左侧文件夹在相应目录删除" class="btn btn-default btn-sm fw400 ml10 removeFolder">
                <span class="fa fa-minus-square pr5"></span> 删除文件夹
            </a>
        </div>
        <div class="topbar-right hidden-xs hidden-sm pr10">
            <a href="javascript:void(0)" title="点击左侧文件夹在相应目录修改" class="btn btn-default btn-sm fw400 ml10 updateFolder">
                <span class="fa fa-pencil pr5"></span> 修改文件夹
            </a>
        </div>
        <div class="topbar-right hidden-xs hidden-sm pr10">
            <a href="javascript:void(0)" title="点击左侧文件夹在相应目录添加" class="btn btn-default btn-sm fw400 ml10 addFolder">
                <span class="fa fa-folder pr5"></span> 添加文件夹
            </a>
        </div>
    </div>
</header>

<div layout:fragment="content">
    <div class="modal fade" id="imgModal" tabindex="-1">
        <!-- 窗口声明 -->
        <div class="modal-dialog modal-sm" style="width:1200px;">
            <!-- 内容 -->
            <div class="modal-content">
                <div class="modal-body" >
                    <img id="img" src="" alt="图片" class="img-rounded img-responsive"/>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <!--左上搜索栏-->
        <div class="admin-form">
            <div class="row">
                <div class="col-md-12">
                    <!-- begin: .smart-widget section -->
                    <div class="smart-widget sm-right">
                        <label class="field">
                            <input name="search" placeholder="请输入文件夹名称..." autocomplete="off" type="text"
                                   class="gui-input"/>
                        </label>
                        <button type="button" class="button" id="btnResetSearch">
                            <i class="fa fa-trash-o"></i>
                        </button>
                    </div>
                    <!-- end: .smart-widget section -->
                </div>
            </div>
        </div>

        <!--文件树-->
        <div id="tree" class="bg-light dark fancytree-ext-filter fancytree-ext-filter-hide">
        </div>
    </div>

    <!-- begin: .tray-center -->
    <div class="col-md-9">
        <div class="panel panel-visible" id="spy1">
            <!-- message listings table -->
            <table class="table table-striped table-hover" id="fileDataTable" cellspacing="0" width="100%">
                <thead>
                <tr>
                    <th>文件名</th>
                    <th>说明</th>
                    <th>创建人</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
                </thead>
            </table>
        </div>
    </div>
    <!-- end: .tray-center -->

    <div id="folder_form" class="popup-basic admin-form mfp-with-anim mfp-hide mw800">
        <div class="panel">
            <div class="panel-heading">
                <span id="popName" class="title">添加文件夹</span>
            </div>
            <form method="get">
                <input type="hidden" id="folderId" />
                <!-- start .form-body section -->
                <div class="panel-body bg-light">
                    <div class="admin-form form-group">
                        <label class="tipLabel"><span class="tipTitle">名称:</span></label>
                        <label class="field prepend-icon">
                            <input type="text" class="gui-input" id="folderName" placeholder="文件夹名称..."/>
                            <label class="field-icon">
                                <i class="fa fa-credit-card"></i>
                            </label>
                        </label>
                    </div>
                    <br/>
                    <div class="section">
                        <label class="tipLabel"><span class="tipTitle">备注:</span></label>
                        <label class="field prepend-icon">
                            <input type="text" class="gui-input" id="folderRemark" placeholder="文件夹备注..."/>
                            <label class="field-icon">
                                <i class="fa fa-credit-card"></i>
                            </label>
                        </label>
                    </div>
                </div>
                <!-- end .form-body section -->
                <div class="panel-footer text-right">
                    <button type="button" onclick="javascript:operaFolder();" class="btn btn-primary btn-xs"> 确定</button>
                    <button type="button" onclick="javascript:$.magnificPopup.close();" class="btn btn-primary btn-xs"> 关闭</button>
                </div>
            </form>
        </div>
    </div>


    <div class="popup-basic admin-form mfp-with-anim mfp-hide mw1200" id="unDemoInit">
        <div class="panel">
            <div class="panel-heading">
                <span class="title">上传文件</span>
            </div>
            <form method="get">
                <input type="hidden" id="uploadFolderId" />
                <!-- start .form-body section -->
                <div class="panel-body bg-light">
                    <table class="table table-striped table-hover" id="datatable" cellspacing="0" width="100%">
                        <thead>
                            <tr>
                                <th width="60px">文件名</th>
                                <th width="100px">备注</th>
                                <th width="100px">状态</th>
                                <th width="50px">操作</th>
                            </tr>
                        </thead>
                        <tbody id="filebody"></tbody>
                    </table>
                </div>
                <!-- end .form-body section -->
                <div class="panel-footer text-right">
                    <input type="file" multiple="multiple" onchange="addFile()" id="multipleFiles" style="opacity: 0;" />
                    <button type="button" onclick="javascript:addFiles();" class="btn btn-primary btn-xs"> 添加</button>
                    <button type="button" onclick="javascript:oneKeyUpload();" class="btn btn-primary btn-xs"> 一键上传</button>
                    <button type="button" onclick="javascript:oneKeyStop();" class="btn btn-primary btn-xs"> 一键暂停</button>
                    <button type="button" onclick="javascript:$.magnificPopup.close();" class="btn btn-primary btn-xs"> 关闭</button>
                </div>
            </form>
        </div>
    </div>

    <div class="popup-basic admin-form mfp-with-anim mfp-hide mw1200" id="flexpaperPop">
        <div class="panel">
            <div class="panel-heading">
                <span class="title">文件预览</span>
            </div>
            <!-- start .form-body section -->
            <div class="panel-body bg-light">
                <div id="flexpaper" style="width:100%;height:700px"></div>
            </div>
        </div>
    </div>

</div>

<script type="text/javascript" layout:fragment="javascript" th:inline="javascript">
    /*<![CDATA[*/
    var fileUrl = /*[[@{/file/getFileByFolderId}]]*/ "/file/getFileByFolderId";
    var delUrl = /*[[@{/file/del}]]*/ "/file/del";
    var removeUrl = /*[[@{/file/removeFolder}]]*/ "/file/removeFolder";
    var fileTreeNodeSearchUrl = /*[[@{/file/getTreeNodeByName}]]*/ "/file/getTreeNodeByName";
    var source = /*[[${yunfileTree}]]*/ [];
    var activeKeyLink = /*[[${activeKeyLink}]]*/ "";
    var reloadActiveKeyUrl = /*[[@{/file/getTreeNodeByActiveKeys}]]*/ "/file/getTreeNodeByActiveKeys";
    var saveActiveKeyLink = /*[[@{/file/saveActiveKeyLink}]]*/ "/file/saveActiveKeyLink";
    var tree;
    var activeKey = [];
    var fileDataTableHolder;
    var fileDownloadPrefix = /*[[${fileDownloadPrefix}]]*/ "";
    jQuery(document).ready(function () {
        if(activeKeyLink){
            activeKey = activeKeyLink.split(",");
        }
        //初始化组织树
        var search = false;
        $("#tree").fancytree({
            source: source,
            ajax: {
                type: "GET",
                cache: true, // false: Append random '_' argument to the request url to prevent caching.
                // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
                dataType: "json" // Expect json format and pass json object to callbacks.
            },
            activate: function (event, data) {
                fileDataTableHolder.ajax.url(fileUrl + "?folderId=" + data.node.key).load();
            },
            lazyLoad: function (event, data) {
                if($.inArray(data.node.key,activeKey) == -1){
                    activeKey.push(data.node.key);
                }
                var activeKeyLink = activeKey.join(",");
                $.ajax({
                    url: saveActiveKeyLink + "?activeKeyLink=" + activeKeyLink,
                    method: 'get'
                });
            },
            postProcess: function (event, data) {
                var responseData = data.response;
                if (!responseData || data.response.code != 1) {
                    new PNotify({
                        title: '系统提示',
                        text: "加载文件树失败",
                        type: 'danger',
                        delay: 1000
                    });
                } else {
                    data.result = responseData.data;
                }
            },
            expand: function (event, data) {
                if (search) {
                    return;
                }
                if($.inArray(data.node.key,activeKey) == -1){
                    activeKey.push(data.node.key);
                }
                var activeKeyLink = activeKey.join(",");
                $.ajax({
                    url: saveActiveKeyLink + "?activeKeyLink=" + activeKeyLink,
                    method: 'get'
                });
            },
            collapse: function (event, data) {
                if (search) {
                    return;
                }
                while($.inArray(data.node.key,activeKey) != -1){
                    activeKey.splice($.inArray(data.node.key,activeKey),1);
                }
                var activeKeyLink = activeKey.join(",");
                $.ajax({
                    url: saveActiveKeyLink + "?activeKeyLink=" + activeKeyLink,
                    method: 'get'
                });
            }
        })

        tree = $("#tree").data("ui-fancytree").getTree();
        //搜索栏绑定事件
        $("input[name=search]").keyup(function (e) {
            search = true;
            activeKey = [];
            $.ajax({
                url: saveActiveKeyLink,
                method: 'get'
            });
            var match = $(this).val();
            if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
                $("button#btnResetSearch").click();
                return;
            }
            $("button#btnResetSearch").attr("disabled", false);
            $.ajax({
                url: fileTreeNodeSearchUrl + "?fileName=" + match,
                dataType: 'json',
                method: 'get',
                async: false,
            }).done(function (data) {
                if (data.code == 1 && data.data) {
                    tree.reload(data.data || []).done(
                        function () {
                            $("#tree").fancytree("getRootNode").visit(function (node) {
                                node.setExpanded(true);
                            });
                        }
                    );
                } else {
                    return []
                }
            });
            search = true;
        }).focus();
        $("button#btnResetSearch").click(function (e) {
            $("input[name=search]").val("");
            tree.clearFilter();
            tree.reload();
        }).attr("disabled", true);

        //初始化表格
        fileDataTableHolder = initDataTable();

        $("a.addFolder").click(function () {
            var node = $("#tree").fancytree("getActiveNode");
            if (!node) {
                new PNotify({
                    title: '温馨提示',
                    text: "请选择一个文件夹",
                    type: 'danger',
                    delay: 1000
                });
                return false;
            }
            $("#popName").html("添加文件夹");
            $("#folderId").val(node.key);
            $("#folderName").val('');
            $("#folderRemark").val('');
            $.magnificPopup.open({
                removalDelay: 100,
                items: {
                    src: "#folder_form"
                },
                callbacks: {
                    beforeOpen: function (e) {
                    }
                },
                midClick: true
            })
        });

        $("a.removeFolder").click(function () {
            var node = $("#tree").fancytree("getActiveNode");
            if (!node) {
                new PNotify({
                    title: '温馨提示',
                    text: "请选择一个文件夹",
                    type: 'danger',
                    delay: 1000
                });
                return false;
            }
            if(node.key == "0"){
                new PNotify({
                    title: '温馨提示',
                    text: "根文件夹不可删除，请重试",
                    type: 'danger',
                    delay: 1000
                });
                return false;
            }
            $.confirm({
                title: '温馨提示',
                content: '是否确认删除：' + node.title + ' ？',
                confirm: function(){
                    $.ajax({
                        url: removeUrl,
                        data: {
                            folderId:  node.key
                        },
                        type: 'post',
                        dataType: 'json',
                        success: function (result) {
                            if (result.code == 1) {
//                                if(node.hasChildren()){
//                                    node.removeChildren();
//                                }
                                node.remove();
                                new PNotify({
                                    title: '系统提示',
                                    text: result.msg,
                                    type: 'success',
                                    delay: 1000
                                });
                            } else {
                                new PNotify({
                                    title: '系统提示',
                                    text: result.msg,
                                    type: 'danger',
                                    delay: 1000
                                });
                            }
                        },
                        error: function () {
                            new PNotify({
                                title: '系统提示',
                                text: "系统异常，请稍后再试",
                                type: 'danger',
                                delay: 1000
                            });
                        }
                    });

                },
                cancel: function(){
                }
            });
        });

        $("a.updateFolder").click(function () {
            var node = $("#tree").fancytree("getActiveNode");
            if (!node) {
                new PNotify({
                    title: '温馨提示',
                    text: "请选择一个文件夹",
                    type: 'danger',
                    delay: 1000
                });
                return false;
            }
            if(node.key == "0"){
                new PNotify({
                    title: '温馨提示',
                    text: "根文件夹不可修改，请重试",
                    type: 'danger',
                    delay: 1000
                });
                return false;
            }
            $("#popName").html("修改文件夹");
            $("#folderId").val(node.key);
            $("#folderName").val(node.title);
            $("#folderRemark").val(node.data.remark);
            $.magnificPopup.open({
                removalDelay: 100,
                items: {
                    src: "#folder_form"
                },
                callbacks: {
                    beforeOpen: function (e) {
                    }
                },
                midClick: true
            })
        });

        $("a.uploadFile").click(function () {
            var node = $("#tree").fancytree("getActiveNode");
            if (!node) {
                new PNotify({
                    title: '温馨提示',
                    text: "请选择一个文件夹",
                    type: 'danger',
                    delay: 1000
                });
                return false;
            }
            $("#uploadFolderId").val(node.key);
            $.magnificPopup.open({
                removalDelay: 100,
                items: {
                    src: "#unDemoInit"
                },
                callbacks: {
                    beforeOpen: function (e) {
                    },
                    beforeClose: function (e) {
                        //暂停所有的上传
                        oneKeyStop();
                        $.each(oneKey, function(key, randomKey){
                            // 删除tr
                            $("#tr_" + randomKey).remove();
                            // 删除表单file
                            files = {};
                            // 删除oneKey
                            oneKey = {};
                            $("#multipleFiles").val('');
                        });
                    }
                },
                midClick: true
            })
            new PNotify({
                title: '温馨提示',
                text: '上传时请勿关闭窗口',
                type: 'warning',
                delay: 1000
            });
        });

        // 激活文件树中的激活点
        if(activeKeyLink){
            reloadTree();
        }

    });

    // 文件夹操作开关
    function operaFolder(){
        if($("#popName").html() == "修改文件夹"){
            updateFolder();
        }else if($("#popName").html() == "添加文件夹"){
            addFolder();
        }
    }

    // 新增文件夹
    var addFolderUrl = /*[[@{/file/addFolder}]]*/ "/file/addFolder";
    function addFolder(){
        var folderId = $("#folderId").val();
        var folderName = $("#folderName").val();
        var folderRemark = $("#folderRemark").val();
        $.ajax({
            url: addFolderUrl,
            type: 'POST',
            dataType: 'json',
            data: {folderId: folderId, folderName: folderName, folderRemark: folderRemark},
            success: function(data){
                if(data.code == "1"){
                    new PNotify({
                        title: '系统提示',
                        text: data.msg,
                        type: 'success',
                        delay: 1000
                    });
                    // 关闭添加窗口
                    $.magnificPopup.close();
                    // 激活当前节点
                    $("input[name=search]").val("");
                    if($.inArray(folderId,activeKey) == -1){
                        activeKey.push(folderId);
                    }
                    var activeKeyLink = activeKey.join(",");
                    $.ajax({
                        url: saveActiveKeyLink + "?activeKeyLink=" + activeKeyLink,
                        method: 'get'
                    });
                    // 刷新文件树
                    reloadTree();
                }else{
                    new PNotify({
                        title: '系统提示',
                        text: data.msg,
                        type: 'danger',
                        delay: 1000
                    });
                }
            }
        });
    }

    // 修改文件夹
    var updateFolderUrl = /*[[@{/file/updateFolder}]]*/ "/file/updateFolder";
    function updateFolder(){
        var folderId = $("#folderId").val();
        var folderName = $("#folderName").val();
        var folderRemark = $("#folderRemark").val();
        $.ajax({
            url: updateFolderUrl,
            type: 'POST',
            dataType: 'json',
            data: {folderId: folderId, folderName: folderName, folderRemark: folderRemark},
            success: function(data){
                if(data.code == "1"){
                    new PNotify({
                        title: '系统提示',
                        text: data.msg,
                        type: 'success',
                        delay: 1000
                    });
                    // 关闭修改窗口
                    $.magnificPopup.close();
                    // 激活当前节点
                    $("input[name=search]").val("");
                    // 刷新文件树
                    reloadTree();
                }else{
                    new PNotify({
                        title: '系统提示',
                        text: data.msg,
                        type: 'danger',
                        delay: 1000
                    });
                }
            }
        });
    }

    // 激活文件树
    function reloadTree(){
        $.ajax({
            url: reloadActiveKeyUrl,
            dataType: 'json',
            method: 'get'
        }).done(function ( data ) {
            if(data.code == 1 && data.data){
                tree.reload( data.data || [])
                        .done(
                                function(){
                                    $("#tree").fancytree("getRootNode").visit(function(node){
                                        if($.inArray(node.key,activeKey) != -1){
                                            node.setExpanded(true);
                                        }
                                    });
                                }
                        );
            }else{
                return []
            }

        })
    }

    // 添加一个文件
    var stop = {};
    var files = {};
    var jsessionId = /*[[${jsessionId}]]*/ "";
    var commonPage;
    var oneKey = {};
    function addFile(){
        var multipleFile = $("#multipleFiles")[0].files;
        if(multipleFile.length == 0){
            return false;
        }
        for(var i = 0; i < multipleFile.length; i++){
            // 判断是否重复添加
            var isRepet = false;
            var file = multipleFile[i];
            var fileSign = hex_sha1(file.lastModified + "_file_" + file.size);
            $.each(files, function(key, val){
                var containterFile = val;
                if(hex_sha1(containterFile.lastModified + "_file_" + containterFile.size) == fileSign){
                    new PNotify({
                        title: '温馨提示',
                        text: "已排除重复文件："  + file.name,
                        type: 'danger',
                        delay: 1000
                    });
                    isRepet = true;
                    return false;
                }
            });
            // 不存在则添加
            if(!isRepet){
                var randomKey = Math.round(Math.random()*1000000000);
                var html = '<tr class="tr_file" id="tr_' + randomKey + '">';
//        html += '<td width="60px"><input type="file" style="height: 22px; width: 200px;" id="file' + randomKey + '" /></td>'; // 文件
                html += '<td width="160px"><span> ' + file.name + '</span></td>'; // 文件名
                html += '<td width="100px"><input type="text" style="height: 22px; width: 200px;" id="ramark' + randomKey + '" /></td>'; // 备注
                html += '<td width="100px"><progress value="0" max="100" style="height: 20px; width: 300px;color:green;" id="prouploadfile' + randomKey + '" /><span id="output' + randomKey + '" style="font-size:20px">0%</span></td>'; // 状态
                html += '<td width="50px"><button id="upload' + randomKey + '">上传</button></td>'; // 操作
                html += '<td width="20px""><span class="glyphicon glyphicon-remove" style="color: rgb(212, 106, 64);" onclick="removeUploadFile(&apos;' + randomKey + '&apos;)" aria-hidden="true"></span></td>';
                html += '</tr>';
                stop['stop' + randomKey] = false;
                files['file' + randomKey] = file;
                $("#filebody").append(html);
                commonPage = new Page(randomKey);
                commonPage.init(randomKey);
                oneKey['oneKey' + randomKey] = randomKey;
            }
        }
    }

    function Page(randomKey){
        this.randomKey = randomKey;
        this.init = function (randomKey) {
            $("#upload" + randomKey).click($.proxy(this.upload, this));
        };
        this.upload = function () {
            var jUploadFolderId = $("#uploadFolderId").val();
            var jUpload = $("#upload" + this.randomKey);
//            var jFile = $("#file" + this.randomKey);
            var jFile = "file" + this.randomKey;
            var jProuploadfile = $("#prouploadfile" + this.randomKey);
            var jOutput = $("#output" + this.randomKey);
            var jStop = "stop" + this.randomKey;
            var jRemark = $(("#ramark" + this.randomKey)).val();
//            if(jFile.val() == ""){
//                new PNotify({
//                    title: '上传失败',
//                    text: "请先选择一个文件",
//                    type: 'danger',
//                    delay: 1000
//                });
//                return false;
//            }
            if(jUpload.html() == "暂停"){
                jUpload.html("上传");
                stop[jStop] = true;
            }else{
                jUpload.html("暂停");
                stop[jStop] = false;
            }
//            var file = jFile[0].files[0],  // 文件对象
            var file = files[jFile],
                    name = file.name,        // 文件名
                    size = file.size;        // 总大小
            var fileSign = hex_sha1(file.lastModified + "_file_" + file.size);
            var shardSize = 4 * 1024 * 1024;    // 以4MB为一个分片
            var start = 0;
            var end = Math.min(size, start + shardSize);
            commonPage.resumable(start, end, file, name, size, fileSign, shardSize, jUpload, jFile, jProuploadfile, jOutput, jStop, jRemark, jUploadFolderId);
            return false;
        };
        this.resumable = function (start, end, file, name, size, fileSign, shardSize, jUpload, jFile, jProuploadfile, jOutput, jStop, jRemark, jUploadFolderId){
            // 构造一个表单
            var form = new FormData();
            form.append("shardData", file.slice(start, end));    // slice方法用于切出文件的一部分
            form.append("fileName", name);
            form.append("totalSize", size); // 文件总大小
            form.append("startSize", start); // 分片文件开始位置
            form.append("fileSign", fileSign);    //TODO 文件签名
            form.append("jsessionId", jsessionId); // sessionId
            form.append("remark", jRemark); // 备注
            form.append("uploadFolderId", jUploadFolderId); // 文件夹ID

            if(end == size){
                jOutput.text("正在转移...");
                jUpload.attr("disabled", "disabled");
            }

            $.ajax({
                url: /*[[@{/file/fileUpload(key=file)}]]*/ "/file/fileUpload?key=file",
                type: "POST",
                data: form,
                async: true, // 异步
                processData: false, // jq对form不进行处理
                contentType: false, // 指定为false才能形成正确的Content-Type
                success: function (data) {
                    jUpload.removeAttr("disabled");
                    data = eval("(" + data + ")");//转换为json对象
                    if(data.code == 1){
                        // 写入成功
                        if(data.data / size == 1){
                            jUpload.html("上传");
                            new PNotify({
                                title: '系统提示',
                                text: "上传成功",
                                type: 'success',
                                delay: 1000
                            });
                            // 上传成功刷新文件列表
                            fileDataTableHolder.ajax.url(fileUrl + "?folderId=" + jUploadFolderId).load();
                        }
                        jOutput.text(Math.ceil((data.data / size) * 100) + "%");
                        jProuploadfile.val(Math.ceil((data.data / size) * 100));
                        // 检查是否暂停
                        if(stop[jStop]){
                            return;
                        }
                        if(data.data / size != 1){
                            start += shardSize;
                            end = Math.min(size, start + shardSize);
                            commonPage.resumable(start, end, file, name, size, fileSign, shardSize, jUpload, jFile, jProuploadfile, jOutput, jStop, jRemark, jUploadFolderId);
                        }
                    } else if(data.code == 80002) {
                        // 重新分片
                        if(data.data == -2){
                            // 系统异常
                            jUpload.html("上传");
                            jProuploadfile.val(0);
                            jOutput.text("0%");
                            new PNotify({
                                title: '系统提示',
                                text: data.msg,
                                type: 'danger',
                                delay: 1000
                            });
                            // 刷新文件列表
                            fileDataTableHolder.ajax.url(fileUrl + "?folderId=" + jUploadFolderId).load();
                        }else if(data.data != -1){
                            // 检查是否暂停
                            if(stop[jStop]){
                                return;
                            }
                            if(data.data / size == 1){
                                jUpload.html("上传");
                                // 上传成功刷新文件列表
                                fileDataTableHolder.ajax.url(fileUrl + "?folderId=" + jUploadFolderId).load();
                            }
                            jOutput.text(Math.ceil((data.data / size) * 100) + "%");
                            jProuploadfile.val(Math.ceil((data.data / size) * 100));
                            start = data.data;
                            end = Math.min(size, start + shardSize);
                            commonPage.resumable(start, end, file, name, size, fileSign, shardSize, jUpload, jFile, jProuploadfile, jOutput, jStop, jRemark, jUploadFolderId);
                        }else if(data.data == -1){
                            jUpload.html("上传");
                            jProuploadfile.val(100);
                            jOutput.text("100%");
                            new PNotify({
                                title: '系统提示',
                                text: "上传成功",
                                type: 'success',
                                delay: 1000
                            });
                            // 上传成功刷新文件列表
                            fileDataTableHolder.ajax.url(fileUrl + "?folderId=" + jUploadFolderId).load();
                        }
                    }
                },
                error: function(){
                    jUpload.html("上传");
                    jProuploadfile.val(0);
                    jOutput.text("0%");
                    new PNotify({
                        title: '系统提示',
                        text: "系统异常，请联系管理员",
                        type: 'danger',
                        delay: 1000
                    });
                }
            });
            return false;
        }
    };

    // 一键上传
    function oneKeyUpload(){
        $.each(oneKey, function(key, randomKey){
            // 未上传的才触发
            var upload = $("#upload" + randomKey);
            if(upload.html() == "上传"){
                upload.click();
            }
        });
    }

    // 一键暂停
    function oneKeyStop(){
        $.each(oneKey, function(key, randomKey){
            // 未暂停的才触发
            var upload = $("#upload" + randomKey);
            if(upload.html() == "暂停"){
                upload.click();
            }
        });
    }

    // 删除上传列表的文件
    function removeUploadFile(randomKey){
        // 上传中的不可删除
        if($("#output" + randomKey).html() == "0%" || $("#output" + randomKey).html() == "100%"){
            // 删除tr
            $("#tr_" + randomKey).remove();
            // 删除表单file
            delete files['file' + randomKey];
            // 删除stops
            delete  stop['stop' + randomKey];
            // 删除oneKey
            delete oneKey['oneKey' + randomKey];
            $("#multipleFiles").val('');
        } else {
            new PNotify({
                title: '系统提示',
                text: "文件已锁定，不可删除",
                type: 'danger',
                delay: 500
            });
        }

    }

    function initDataTable() {
        var fileDataTable = $('#fileDataTable').DataTable({
            ordering: false,
            language: {
                "lengthMenu": "显示条目 _MENU_ ",
                "zeroRecords": "没有数据",
                "info": "当前显示 _START_ 到 _END_ 条，第 _PAGE_ / _PAGES_ 页，总计 _TOTAL_ 条",
                "infoEmpty": "",
                "infoFiltered": "",
                "loadingRecords": "请稍候 - 加载中...",
                "search": "搜索",
                "paginate": {
                    "first": "首页",
                    "last": "最后一页",
                    "next": "下一页",
                    "previous": "上一页"
                }
            }, ajax: {
                "url": fileUrl,
                "type": "GET",
                "dataSrc": function (json) {
                    if (json.code == 1) {
                        return json.data || [];
                    } else {
                        new PNotify({
                            title: '系统提示',
                            text: json.msg,
                            type: 'danger',
                            delay: 1000
                        });
                    }
                    return [];
                }
            }, columns: [
                {"data": "fileName"},
                {"data": "remark"},
                {"data": "createPeople"},
                {"data": "createTime"},
                {
                    "data": "fileUrl",
                    render: function (data, type ,row) {
                        var sourcefile = data.split("#%&#")[0];
                        var pattern = new RegExp(/\.(gif|bmp|svg)\b$/);
                        var swf = data.split("#%&#")[1];
                        var opera = "";
                        if(data !=null && swf != null && swf != undefined){
                            opera += "&nbsp;<a class='btn btn-primary btn-xs' href='javascript:void(0)' onclick='showSwf(&apos;" + swf + "&apos;)'>文件预览</a>";
                        }
                        if(data != null && data != '' && pattern.test(data)){
                            opera += "&nbsp;<a class='btn btn-primary btn-xs' href='javascript:void(0)' data-toggle='modal' data-target='#imgModal' onclick='$(&apos;#img&apos;).attr(&apos;src&apos;,&apos;" + fileDownloadPrefix + sourcefile + "&apos;)'>文件预览</a>";
                        }
                        opera += "&nbsp;<a class='btn btn-primary btn-xs' target='_blank' href='" + fileDownloadPrefix + sourcefile + "?attname=" + row.fileName + "'>下载</a>&nbsp;<a class='btn btn-primary btn-xs' href='javascript:void(0)' onclick='delFile(" + row.fileId + ',"' + row.fileName + '"' + ")'>删除</a>";
                        return opera;
                    }
                },
            ], columnDefs: [{
//                "render": $.fn.dataTable.render.ellipsis(8),
//                "targets": 3
            }]
        });
        return fileDataTable;
    }


    //删除文件
    function delFile(fileId, fileName) {
        if(!fileId){
            new PNotify({
                title: '温馨提示',
                text: "文件ID不能为空",
                type: 'danger',
                delay: 1000
            });
            return;
        }
        var node = $("#tree").fancytree("getActiveNode");
        if (!node) {
            new PNotify({
                title: '温馨提示',
                text: "请选择一个文件夹",
                type: 'danger',
                delay: 1000
            });
            return false;
        }
        $.confirm({
            title: '温馨提示',
            content: '是否确认删除：' + fileName + ' ？',
            confirm: function(){
                $.ajax({
                    url: delUrl,
                    data: {
                        fileId:  fileId
                    },
                    type: 'post',
                    dataType: 'json',
                    success: function (result) {
                        if (result.code == 1) {
                            new PNotify({
                                title: '系统提示',
                                text: result.msg,
                                type: 'success',
                                delay: 1000
                            });
                            // 删除成功刷新文件列表
                            fileDataTableHolder.ajax.url(fileUrl + "?folderId=" + node.key).load();
                        } else {
                            new PNotify({
                                title: '系统提示',
                                text: result.msg,
                                type: 'danger',
                                delay: 1000
                            });
                        }
                    },
                    error: function () {
                        new PNotify({
                            title: '系统提示',
                            text: "系统异常，请稍后再试",
                            type: 'danger',
                            delay: 1000
                        });
                    }
                });

            },
            cancel: function(){
            }
        });
    }

    function addFiles(){
        return $("#multipleFiles").click();
    }

    function showSwf(swf){
        $.magnificPopup.open({
            removalDelay: 100,
            items: {
                src: "#flexpaperPop"
            },
            callbacks: {
                beforeOpen: function (e) {
                }
            },
            midClick: true
        });

        $("#flexpaper").FlexPaperViewer({
            config : {
                SWFFile : fileDownloadPrefix + swf,
                Scale : 0.6,
                ZoomTransition : 'easeOut',
                ZoomTime : 0.5,
                ZoomInterval : 0.2,
                FitPageOnLoad : true,
                FitWidthOnLoad : true,
                FullScreenAsMaxWindow : false,
                ProgressiveLoading : false,
                MinZoomSize : 0.2,
                MaxZoomSize : 5,
                SearchMatchAll : false,
                InitViewMode : 'Portrait',
                RenderingOrder : 'flash',
                StartAtPage : '',
                ViewModeToolsVisible : true,
                ZoomToolsVisible : true,
                NavToolsVisible : true,
                CursorToolsVisible : true,
                SearchToolsVisible : true,
                WMode : 'window',
                localeChain : 'zh_CN',
                jsDirectory : /*[[@{/resources/flexpaper/js/}]]*/ "/resources/flexpaper/js/",
                cssDirectory : /*[[@{/resources/flexpaper/css/}]]*/ "/resources/flexpaper/css/"
            }
        });
    }

   /*]]>*/
</script>

</body>
</html>